package com.luyu.datapermission;


import cn.hutool.core.collection.CollUtil;
import com.luyu.entity.User;
import com.luyu.service.IUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理单位下的数据权限字段
 */
@Service
public class UnitFieldDataPermissionService extends AbsFieldDataPermissionService{
    private final String FILED_NAME="unit_id";

    private IUnitService unitService;

    @Autowired
    public UnitFieldDataPermissionService(IUnitService unitService) {
        this.unitService = unitService;
    }

    @Override
    public String supportFiled() {
        return FILED_NAME;
    }

    @Override
    public String getSql() {
        // 获取当前单位及所有的子单位的sql
        User details = (User) SecurityContextHolder.getContext().getAuthentication().getDetails();
        // String strSql= listIdsSql(FILED_NAME,List.of(details.getUnitId()));
        String strSql= listIdsSql(FILED_NAME,unitService.listIdsByParentUnitId(details.getUnitId()));
        return strSql;
    }


    private  String listIdsSql(String fieldStr,List<Long> list){
        String str="";
        if (CollUtil.isEmpty(list)) {
            return str;
        }
        for (Long t : list) {
            str+=str+t.toString()+",";
        }
        str=" "+ fieldStr+ " in ("+str.substring(0, str.length() - 1)+")";
        return str;
    }

}
